import { Request, Response } from 'express';
import { Category, ICategory } from '../models/Category';

interface AuthenticatedRequest extends Request {
  user?: {
    userId: string;
    role: string;
  };
}

export class CategoryController {
  // 获取所有分类
  public getAll = async (req: Request, res: Response): Promise<void> => {
    try {
      const { type } = req.query;
      
      const query: any = { isActive: true };
      if (type) {
        query.type = type;
      }

      const categories = await Category.find(query).sort({ type: 1, order: 1 });

      // 按类型分组
      const groupedCategories = categories.reduce((acc: any, category) => {
        if (!acc[category.type]) {
          acc[category.type] = [];
        }
        acc[category.type].push(category);
        return acc;
      }, {});

      res.json({
        success: true,
        data: {
          categories,
          grouped: groupedCategories
        }
      });
    } catch (error) {
      console.error('获取分类列表错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 获取单个分类
  public getById = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;

      const category = await Category.findById(id);
      if (!category) {
        res.status(404).json({
          success: false,
          message: '分类不存在'
        });
        return;
      }

      res.json({
        success: true,
        data: category
      });
    } catch (error) {
      console.error('获取分类详情错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 创建分类（管理员权限）
  public create = async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    try {
      if (req.user?.role !== 'admin') {
        res.status(403).json({
          success: false,
          message: '没有权限创建分类'
        });
        return;
      }

      const { name, type, description, order } = req.body;

      // 检查分类名是否已存在
      const existingCategory = await Category.findOne({ name, type });
      if (existingCategory) {
        res.status(400).json({
          success: false,
          message: '该分类名称已存在'
        });
        return;
      }

      const category = new Category({
        name,
        type,
        description,
        order: order || 0
      });

      await category.save();

      res.status(201).json({
        success: true,
        message: '分类创建成功',
        data: category
      });
    } catch (error) {
      console.error('创建分类错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 更新分类（管理员权限）
  public update = async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    try {
      if (req.user?.role !== 'admin') {
        res.status(403).json({
          success: false,
          message: '没有权限更新分类'
        });
        return;
      }

      const { id } = req.params;
      const updateData = req.body;

      const category = await Category.findById(id);
      if (!category) {
        res.status(404).json({
          success: false,
          message: '分类不存在'
        });
        return;
      }

      // 如果更新名称，检查是否重复
      if (updateData.name && updateData.name !== category.name) {
        const existingCategory = await Category.findOne({ 
          name: updateData.name, 
          type: updateData.type || category.type,
          _id: { $ne: id }
        });
        if (existingCategory) {
          res.status(400).json({
            success: false,
            message: '该分类名称已存在'
          });
          return;
        }
      }

      const updatedCategory = await Category.findByIdAndUpdate(
        id,
        updateData,
        { new: true, runValidators: true }
      );

      res.json({
        success: true,
        message: '分类更新成功',
        data: updatedCategory
      });
    } catch (error) {
      console.error('更新分类错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 删除分类（管理员权限）
  public delete = async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    try {
      if (req.user?.role !== 'admin') {
        res.status(403).json({
          success: false,
          message: '没有权限删除分类'
        });
        return;
      }

      const { id } = req.params;

      const category = await Category.findById(id);
      if (!category) {
        res.status(404).json({
          success: false,
          message: '分类不存在'
        });
        return;
      }

      // 软删除：设置为非活跃状态
      await Category.findByIdAndUpdate(id, { isActive: false });

      res.json({
        success: true,
        message: '分类删除成功'
      });
    } catch (error) {
      console.error('删除分类错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 批量更新分类顺序（管理员权限）
  public updateOrder = async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    try {
      if (req.user?.role !== 'admin') {
        res.status(403).json({
          success: false,
          message: '没有权限更新分类顺序'
        });
        return;
      }

      const { categories } = req.body; // [{ id, order }, ...]

      if (!Array.isArray(categories)) {
        res.status(400).json({
          success: false,
          message: '请提供有效的分类顺序数据'
        });
        return;
      }

      // 批量更新
      const updatePromises = categories.map(({ id, order }) => 
        Category.findByIdAndUpdate(id, { order })
      );

      await Promise.all(updatePromises);

      res.json({
        success: true,
        message: '分类顺序更新成功'
      });
    } catch (error) {
      console.error('更新分类顺序错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 初始化默认分类数据
  public initializeDefaultCategories = async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    try {
      if (req.user?.role !== 'admin') {
        res.status(403).json({
          success: false,
          message: '没有权限初始化分类数据'
        });
        return;
      }

      const defaultCategories = [
        // 学科分类
        { name: '语文', type: 'subject', order: 1 },
        { name: '数学', type: 'subject', order: 2 },
        { name: '英语', type: 'subject', order: 3 },
        { name: '物理', type: 'subject', order: 4 },
        { name: '化学', type: 'subject', order: 5 },
        { name: '生物', type: 'subject', order: 6 },
        { name: '历史', type: 'subject', order: 7 },
        { name: '地理', type: 'subject', order: 8 },
        { name: '政治', type: 'subject', order: 9 },
        
        // 年级分类
        { name: '一年级', type: 'grade', order: 1 },
        { name: '二年级', type: 'grade', order: 2 },
        { name: '三年级', type: 'grade', order: 3 },
        { name: '四年级', type: 'grade', order: 4 },
        { name: '五年级', type: 'grade', order: 5 },
        { name: '六年级', type: 'grade', order: 6 },
        { name: '七年级', type: 'grade', order: 7 },
        { name: '八年级', type: 'grade', order: 8 },
        { name: '九年级', type: 'grade', order: 9 },
        { name: '高一', type: 'grade', order: 10 },
        { name: '高二', type: 'grade', order: 11 },
        { name: '高三', type: 'grade', order: 12 },
        
        // 课程类型
        { name: '新课讲授', type: 'courseType', order: 1 },
        { name: '复习课', type: 'courseType', order: 2 },
        { name: '习题课', type: 'courseType', order: 3 },
        { name: '实验课', type: 'courseType', order: 4 },
        { name: '活动课', type: 'courseType', order: 5 },
        { name: '测验课', type: 'courseType', order: 6 }
      ];

      const createPromises = defaultCategories.map(async (categoryData) => {
        const existing = await Category.findOne({ 
          name: categoryData.name, 
          type: categoryData.type 
        });
        if (!existing) {
          return Category.create(categoryData);
        }
        return null;
      });

      const results = await Promise.all(createPromises);
      const created = results.filter(result => result !== null);

      res.json({
        success: true,
        message: `成功初始化 ${created.length} 个分类`,
        data: { created: created.length, total: defaultCategories.length }
      });
    } catch (error) {
      console.error('初始化分类数据错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };
}